#include "stack.h"

void STinit(stack* ps)
{
	assert(ps);
	ps->arr = NULL;
	ps->capacity = ps->top = 0;
}

void STdestroy(stack* ps)
{
	assert(ps);
	free(ps->arr);
	ps->arr = NULL;
	ps->capacity = ps->top = 0;
}

void STpush(stack* ps, STdatatype x)
{
	assert(ps);
	if (ps->capacity == ps->top)
	{
		int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		stack* tmp = (stack*)realloc(ps->arr, newcapacity * sizeof(STdatatype));
		if (tmp == NULL)
		{
			perror("realloc failed !\n");
			exit(1);
		}
		ps->arr = tmp;
		ps->capacity = newcapacity;
		ps->arr[ps->top] = x;
		ps->top++;
	}
	else
	{
		ps->arr[ps->top] = x;
		ps->top++;
	}
}

void Printf(stack* ps)
{
	assert(ps);
	for (int i = 0; i < ps->top; i++)
		printf("%d -> ", ps->arr[i]);
	printf("\n");
}

void STpop(stack* ps)
{
	assert(ps);
	assert(ps->top != 0);
	ps->top--;
}

STdatatype getTop(stack* ps)
{
	assert(ps);
	return ps->arr[ps->top - 1];
}

int Rreturn(stack* ps)
{
	assert(ps);
	return ps->top;
}

bool ST(stack* ps)
{
	assert(ps);
	return ps->top == 0;
}
